import { defineStore } from 'pinia';
import { getItem, setItem, removeItem } from '@/utils/storage';
import { loginApi } from '@/api/controller';
import { commonOptions } from './commonOptions';
import useRouter from '@/router';
import { ruleRoter, routeslist } from '@/router';
import watermark from 'watermark-h5';
import { RouteRecordRaw } from 'vue-router';
import { ToastWarning, Toastloading } from '@/utils/public';
export const token = 'SET_TOKEN';
export const userStore = defineStore('user', {
  state: () => ({
    SET_TOKEN:'' || getItem(token),
    roles: [] as Array<any>,
    userName: '' as string,
    avatar: '' as string,
    oss_url: '' as string,
    kkaudio_api: '' as string,
    menuList: [] as Array<any>,
    admin_id:''
  }),
  actions: {
    Login(userInfo:any) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
        loginApi.login(username, userInfo.password).then(response => {
          const data = response.data
          setItem(token,data.api_token);
          this.SET_TOKEN = data.api_token
          resolve(true);
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo() {
      return new Promise((resolve, reject) => {
        loginApi.getInfo(this.SET_TOKEN).then(response => {
          const { roles=[], name='', avatar='', config='', id:admin_id ='' } = response.data
          const { oss_url='', kkaudio_api='' } = config;
          this.admin_id = admin_id
          let accessedRoutes = [] as Array<RouteRecordRaw>;
          if (Array.isArray(roles) && roles.length > 0) { // 验证返回的roles是否是一个非空数组
            this.roles = roles;
            this.romoveRouterlist()
            // 追加路由
            accessedRoutes = this.filterAsyncRoutes(ruleRoter, roles);
            accessedRoutes.forEach(route => useRouter.addRoute(route));
            // 菜单列表
            this.menuList = [...routeslist , ...accessedRoutes];
          } else {
            ToastWarning('暂无权限')
            Toastloading().close()
            this.FedLogOut()
            reject('getInfo: roles must be a non-null array !')
          }
          this.userName = name;
          this.avatar = avatar;
          this.oss_url = oss_url;
          this.kkaudio_api = kkaudio_api;
          resolve(accessedRoutes)
          commonOptions().getRechargeChannels()
        }).catch(error => {
          reject(error)
        })
      })
    },
    hasPermission(roles: any[], route: { meta: { role: string | any[]; }; }) {
      if (route.meta && route.meta.role) {
        return roles.some((role: any) => route.meta.role.includes(role))
      } else {
        return true
      }
    },
    filterAsyncRoutes(routes: any[], roles: any[]) {
      const list:any = []
      routes.forEach((route: any) => {
        let tmp = { ...route }
        if (this.hasPermission(roles, tmp)) {
          if (Array.isArray(tmp.children)) {
            tmp.children = this.filterAsyncRoutes(tmp.children, roles)
          }
          list.push(tmp)
        }
      })
      return list
      
    },
    // 删除所有动态路由
    romoveRouterlist() {
      ruleRoter.forEach((item:any) => {
        const routeSet = useRouter.hasRoute(item.name)
        if(routeSet) useRouter.removeRoute(item.name)
      })
    },
    FedLogOut() {
      useRouter.push({path:'/login'});
      this.SET_TOKEN = '';
      this.romoveRouterlist()
      this.roles = []
      this.menuList = []
      watermark.clear();
      removeItem(token);
    }
  },
})